package com.example.controller;


import com.example.config.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/common")
@CrossOrigin(origins = "*", maxAge = 3600)   //解决跨域问题
public class UploadController {


    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件删除


        //获取原始的文件名
        String originalFilename = file.getOriginalFilename();
        //获取上传的文件后缀
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuidFileName= UUID.randomUUID().toString()+extName;
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在需要创建
            dir.mkdirs();
        }
        File targetFile = new File(dir, uuidFileName);
        file.transferTo(targetFile);
        return R.success(uuidFileName);
    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response) throws IOException {
        File file = new File(basePath,name);
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buf=new byte[1024];
        int length=0;
        while ((length=fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,length);
        }
        fileInputStream.close();
    }


}
